package com.bst.etl.core.masterworker;

import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Master {

    private ConcurrentLinkedQueue<JobParameters> workQueue = new ConcurrentLinkedQueue<JobParameters>();
    private HashMap<String,Thread> workers = new HashMap<>();
    private ConcurrentHashMap<Long, JobExecution> resultMap = new ConcurrentHashMap<Long, JobExecution>();

    public Master(Worker worker,int workerCount){
        //在worker中添加两个引用  workQueue用于任务的领取  resultMap用于任务的提交
        worker.setWorkerQueue(this.workQueue);
        worker.setResultMap(this.resultMap);
        for (int i = 0; i < workerCount; i++) {
            workers.put("node"+i, new Thread(worker));
        }
    }

    public void execute() {
        for (Map.Entry<String,Thread> me: workers.entrySet()) {
            me.getValue().start();
        }
    }

    public void submit(JobParameters task){
        workQueue.add(task);
    }

    public boolean isCompleted() {
        for(Map.Entry<String,Thread> thread:workers.entrySet()) {
            if(thread.getValue().getState()!=Thread.State.TERMINATED) {
                return false;
            }
        }
        return true;
    }

    public String getResult() {
        for(JobExecution r : resultMap.values()) {
            if(!(BatchStatus.COMPLETED.name().equals(r.getStatus().name()))) {
                return BatchStatus.FAILED.name();
            }
        }
        return BatchStatus.COMPLETED.name();
    }
}
